<template>
  <div class="app-container">
    <el-table :data="detailList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="isRowSelectable" align="center" />
      <el-table-column prop="orderSerial" label="订单编号" align="left">
      </el-table-column>
      <el-table-column prop="crTime" label="创建时间" align="left">
        <template slot-scope="scope">
          {{removeSeconds(scope.row.crTime)}}
        </template>
      </el-table-column>
      <el-table-column prop="storeName" label="店铺名称" align="left">
      </el-table-column>
      <el-table-column prop="backSerial" align="left" label="商品" width="350">
        <template slot-scope="scope">
          <div style="display: flex;">
            <div style="width: 100px;height: 100px;">
              <el-image style="width: 100px; height: 100px" :src="scope.row.mainPic"
                :preview-src-list="[scope.row.mainPic]" fit="contain"></el-image>
            </div>
            <div
              style="width: 250px;display: flex;flex-direction:column;justify-content: center;padding-left: 10px;padding-right: 20px;box-sizing: border-box;">
              <div>
                <el-tooltip class="item" effect="dark" placement="top" :content="scope.row.productName">
                  <div class="cell-ellipsis">{{ scope.row.productName }}</div>
                </el-tooltip>
              </div>
              <div><el-tooltip class="item" effect="dark" placement="top" :content="scope.row.specification">
                  <div class="cell-ellipsis">{{ scope.row.specification }}</div>
                </el-tooltip></div>
            </div>
          </div>
        </template>
      </el-table-column>


      <el-table-column prop="salePrice" label="商品金额" align="left">
        <template slot-scope="scope">
          <span style="font-weight: bold;color: #f00;">¥{{scope.row.salePrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productNumb" label="商品数量" align="left">
        <template slot-scope="scope">
          <span>x{{scope.row.productNumb}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productRemark" label="备注" align="left">
      </el-table-column>
      <!-- 拼接 -->
      <el-table-column prop="emsFrom" label="买家收货信息" align="left">
        <template slot-scope="scope">
          {{scope.row.toUser}}{{scope.row.toPhone}}{{scope.row.emsToPrefix}}{{scope.row.emsTo}}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="物流状态" align="center">
        <template slot-scope="scope">
          <el-tag size="medium">
            <dict-tag :options="dict.type.ems_status" :value="scope.row.status" />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="emsFrom" label="商品发货地址" align="left">
        <template slot-scope="scope">
          <!-- {{scope.row.toUser}}{{scope.row.toPhone}}{{scope.row.emsToPrefix}}{{scope.row.emsTo}} -->
          {{scope.row.toUser}}{{scope.row.toPhone}}{{scope.row.emsFrom}}
        </template>
      </el-table-column>
      <!-- 拼接 -->
      <el-table-column prop="backFromPrefix" label="商品退货地址" align="left">
        <template slot-scope="scope">
          {{scope.row.toUser}}{{scope.row.toPhone}}{{scope.row.backFromPrefix}}{{scope.row.backFrom}}
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 40px;">
      买家收货信息：{{detailsShop.toUser}}-{{detailsShop.toPhone}}-{{detailsShop.htEmsList[0].emsToPrefix}}-{{detailsShop.emsTo}}
    </div>
    <div style="margin-top: 30px;margin-bottom: 30px;font-weight: bold;">选择发货方式</div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
      <el-form-item label="快递公司" prop="emsCode">
        <el-col :span="8">
          <el-select style="width: 100%;" v-model="ruleForm.emsCode" clearable placeholder="请选择快递公司">
            <el-option v-for="dict in emsList" :key="dict.emsCode" :label="dict.emsName"
              :value="dict.emsCode"></el-option>
          </el-select>
        </el-col>
        <el-col :span="16">
          <div v-if="ruleForm.emsCode=='jd'">
            <div style="padding-left: 10px;">快递费余额
              <span
                style="color: red;font-weight: bold;font-size: 18px;padding-left: 10px;padding-right: 10px;">¥{{expressFeeBalance}}</span>
                <span
                @click="rechargeBtn" class="rechargeBtn">充值</span>
                <span
                v-if="expressFeeBalance<100">提示：快递费余额不足100元，请商家速充值以免影响发货</span>
              </div>
            <!-- <div>快递费余额{{expressFeeBalance}}<span @click="rechargeBtn" class="rechargeBtn">充值</span><span
                v-if="expressFeeBalance<100">提示：快递费余额不足100元，请商家速充值以免影响发货</span></div> -->
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="请输入快递单号" prop="emsNum">
        <el-col :span="8">
          <el-input :disabled="ruleForm.emsCode=='jd'" v-model="ruleForm.emsNum"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item v-if="ruleForm.emsCode=='jd'" label="日期">
        <el-col :span="8">
          <el-form-item prop="time">
            <el-date-picker v-model="ruleForm.startTime" type="date" placeholder="选择开始时间"
              @change="handleStartTimeChange">
            </el-date-picker>
            <el-date-picker v-model="ruleForm.endTime" :picker-options="endPickerOptions" type="date"
              placeholder="选择结束时间">
            </el-date-picker>
            <div>预估京东快递价格<span
                style="color: red;font-weight: bold;font-size: 18px;padding-left: 10px;padding-right: 10px;">¥{{totalFreightPre}}</span><span
                style="color: #888;">实际以快递员报价为准</span></div>
            <div>如果选择京东快递，无需手动输入运单号，因为京东物流系统会自动生成并关联运单号。</div>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item>
        <!-- <el-button :disabled="ruleForm.emsCode&&ruleForm.emsCode!='jd'&&!ruleForm.emsNum ? true : false" type="primary"
          @click="submitForm('ruleForm')">确认并发货</el-button> -->
        <el-button type="primary" @click="submitForm('ruleForm')">确认并发货</el-button>
        <el-button @click="resetCancel">取消</el-button>
      </el-form-item>
    </el-form>


    <el-dialog title="快递费" :visible.sync="dialogVisible" @close="dialogVisible = false" width="40%">
      <div style="max-height: 550px;overflow: auto;">
        <p>尊敬的商家：您好！</p>
        <p> 一、平台收款信息及账号</p>
        <p><b>对公账号：河南振乡甄选网络科技有限公司</b></p>
        <p><b>收款账号：462190100100277160</b></p>
        <p><b>开户银行：兴业银行郑州航海中路支行</b></p>
        <p>备注信息：【店铺名称】+快递费（注：请务必在转账时准确填写您的店铺名称及“快递费”作为备注，以便我们快速准确地核对您的款项，避免转账延误或错误处理。）</p>
        <p>二、注意事项</p>
        <p>转账前核对信息：请您在转账前再次确认上述收款信息是否准确无误，特别是收款账号、开户银行及备注信息，以免因信息错误导致转账失败或延误。</p>
        <p>及时通知：转账完成后，建议您通过平台的联系方式或客服渠道及时通知我们，告知转账时间、金额及转账凭证，以便我们尽快为您充值快递费余额。</p>
        <p>充值时效：我们会在收到您转账通知并核对无误后的24小时内完成快递费余额的充值。</p>
        <p>余额查询：您可以在平台商家后台查看快递费余额的充值情况及使用记录，确保您的资金安全。</p>
      </div>
      <span slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>


    <!-- <el-dialog title="快递费" :visible.sync="dialogVisible" @close="dialogVisible = false" width="40%">
      <div style="max-height: 550px;overflow: auto;">
        尊敬的商家您好，
        请注意，您的当前快递费余额不够100，账户余额现已低于平台要求最低金额，以免耽误您的商品发货请提前充值。
        费用说明：需特别提醒，订单物流状态转为“在途”，实际快递费用将从余额中直接扣除。实际快递费用以快递员最终确认为准。系统预扣的费用仅为初步估算，实际费用可能存在差异。
        为避免服务中断或产生不必要的麻烦，建议您尽快充值以确保有足够的余额支付可能产生的快递费用差额。感谢您的理解与支持，我们期待继续为您提供优质的服务！
      </div>
      <span slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog> -->

  </div>
</template>

<script>
  import store from "@/store";
  import {
    getemsList,
    getEmsListDetails,
    geteditList,
    getEmsJdPrice
  } from "@/api/store/orderhead";
  export default {
    name: "productDeliveryDetails",
    dicts: ['product_flag', 'ems_status'],
    data() {
      return {
        groundVisible: false, //上架
        offShelfVisible: false, //下架
        nestedTableData: [],
        dictArr: [{
            value: '0',
            label: '未生效'
          },
          {
            value: '1',
            label: '已生效'
          }
        ],
        tableData: [],
        editForm: {},
        dialogVisible: false,
        dialogTitle: '',
        tabPosition: 'left',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          storeName: '',
          productCode: '',
          productFlag: '',
          productName: '',
        },
        // 表单参数
        form: {},
        xlsFile: [],
        fileListN: [],
        allList: [],
        propsObj: {
          label: 'text',
          value: 'value',
          option: 'children',
        },
        detailsShop: {},
        detailList: [],
        emsList: [],
        ruleForm: {
          emsCode: '',
          emsNum: '',
          startTime: '',
          endTime: ''
        },
        rules: {
          emsCode: [{
            required: true,
            message: '请选择快递公司',
            trigger: 'change'
          }, ],
        },
        emsFromArrs: [],
        addressXz: [],
        endPickerOptions: {
          disabledDate: time => {
            if (this.ruleForm.startTime) {
              return time.getTime() < new Date(this.ruleForm.startTime).getTime();
            }
          }
        },
        privinceList: store.getters.privinceList,
        cityList: store.getters.cityList,
        countyList: store.getters.countyList,
        totalFreightPre: null,
        expressFeeBalance: null,
      };
    },
    created() {
      console.log(this.privinceList)
      console.log(this.cityList)
      console.log(this.countyList)
      const orderSerial = this.$route.params && this.$route.params.orderSerial;
      if (orderSerial) {
        this.getDetails(orderSerial)
      }

    },
    methods: {
      getEmsJdPrice() {
        let params = {
          "fromUser": this.detailList[0].fromUser,
          "emsFrom": this.detailList[0].emsFrom,
          "fromPhone": this.detailList[0].fromPhone,
          "toProvince": this.detailList[0].toProvince,
          "toCity": this.detailList[0].toCity,
          "toCounty": this.detailList[0].toCounty,
          "emsTo": this.detailList[0].emsTo,
          "toUser": this.detailList[0].toUser,
          "toPhone": this.detailList[0].toPhone,
          "productName": this.detailList[0].productName,
          "storeCode": this.detailList[0].storeCode,
        }
        getEmsJdPrice(params).then(response => {
          if (response.code == '200') {
            this.totalFreightPre = response.data.totalFreightPre
            if (response.data.expressFeeBalance) {
              this.expressFeeBalance = Number(response.data.expressFeeBalance)
            }
          }
        });
      },
      isRowSelectable(row) {
        // productStatus  商品状态：0-默认 1-退款中 2-已退款
        return row.status !== '17' && (row.productStatus != '1' || row.productStatus != '2');
      },
      getSHXMen(data) {
        console.log(data, 'data')
        let toProvince = this.getProvinceName(data.toProvince) ? this.getProvinceName(data.toProvince) : ''
        let toCity = this.getCityName(data.toCity) ? this.getCityName(data.toCity) : ''
        let toCounty = this.getCountyName(data.toCounty) ? this.getCountyName(data.toCounty) : ''
        let res = toProvince + toCity + toCounty
        return res
      },
      getSHX(data) {
        let toProvince = this.getProvinceName(data.backProvinceId) ? this.getProvinceName(data.backProvinceId) : ''
        let toCity = this.getCityName(data.backCityId) ? this.getCityName(data.backCityId) : ''
        let toCounty = this.getCountyName(data.backCountyId) ? this.getCountyName(data.backCountyId) : ''
        let res = toProvince + toCity + toCounty
        return res
      },
      handleStartTimeChange(value) {
        if (this.ruleForm.endTime && new Date(value).getTime() > new Date(this.ruleForm.endTime).getTime()) {
          this.ruleForm.endTime = ''; // 重置结束时间以确保大于等于开始时间
        }
      },
      handleDateChange(value) {
        if (value) {
          const currentDate = new Date();
          if (value < currentDate) {
            this.$message.error('选择的时间必须大于当前时间');
            this.ruleForm.time = '';
          } else {}
        }
      },
      getDetails(orderSerial) {
        let params = {
          orderSerial: orderSerial
        }
        getEmsListDetails(params).then(response => {
          console.log(response, 'response')
          if (response.code == '200') {
            this.detailsShop = response.data[0]
            this.detailList = this.detailsShop.htEmsList
            this.getEmsJdPrice()
          }
        });
        getemsList().then(response => {
          this.emsList = response.data
        })
      },
      resetCancel() {
        this.$router.go(-1)
      },
      submitForm(formName) {
        if (this.emsFromArrs.length == 0) {
          this.$modal.msgError('请选择发货商品');
          return
        }
        if (this.emsFromArrs.some((e) => this.emsFromArrs.filter((e1) => e1.emsFrom != e.emsFrom).length > 0)) {
          this.$modal.msgError('由于发货地址不同，无法合并发货');
          return
        } else {
          console.log('v 相同');
        }


        if (this.ruleForm.emsCode == 'jd' && this.expressFeeBalance <= 100) {
          this.$message({
            showClose: true,
            dangerouslyUseHTMLString: true,
            message: "<p>尊敬的商家您好，</p><br><p>请注意，您的当前快递费余额不够100，账户余额现已低于平台要求最低金额，以免耽误您的商品发货请提前充值。</p><br><p>费用说明：需特别提醒，订单物流状态转为“在途”，实际快递费用将从余额中直接扣除。</p><br><p>实际快递费用以快递员最终确认为准。系统预扣的费用仅为初步估算，实际费用可能存在差异。</p><br><p>为避免服务中断或产生不必要的麻烦，建议您尽快充值以确保有足够的余额支付可能产生的快递费用差额。</p><br><p>感谢您的理解与支持，我们期待继续为您提供优质的服务！</p>",
            type: 'error'
          });
          return
        }

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.getSubmit()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleSelectionChange(selection) {
        console.log(selection, 'selection')
        let arr = selection
        this.emsFromArrs = arr
        if (arr.some((e) => arr.filter((e1) => e1.emsFrom != e.emsFrom).length > 0)) {
          this.$modal.msgError('由于发货地址不同，无法合并发货');
          return
        } else {
          console.log('v 相同');
        }
      },
      getSubmit() {
        let arr = this.emsFromArrs.map(item => {
          return Object.assign({}, {
            "emsId": item.emsId,
            "orderSerial": item.orderSerial, // 订单编号
            "productName": item.productName, //商品标题
            "emsCom": this.ruleForm.emsCode, //快递公司
            "emsNum": this.ruleForm.emsNum, //快递单号
            "fromUser": item.fromUser, // 发货人
            "fromPhone": item.fromPhone, //发货电话
            "emsFrom": item.emsFrom, //发货地址
            "toUser": item.toUser, //收货人人
            "toPhone": item.toPhone, //收货电话
            "emsTo": item.emsTo, //收货详细地址
            "startDate": this.parseTime(this.ruleForm.startTime, '{y}-{m}-{d}') + this
              .getCurrentDateTime(), // 预计取件时间
            "overDate": this.parseTime(this.ruleForm.startTime, '{y}-{m}-{d} {h}:{i}:{s}'), // 最迟取件时间，
            "toCity": this.detailsShop.toCity,
            "toCounty": this.detailsShop.toCounty,
            "toProvince": this.detailsShop.toProvince,
          })
        })
        let params = {
          htEmsList: arr
        }
        geteditList(params).then(response => {
          if (response.code == '200') {
            this.$modal.msgSuccess('提交成功');
            this.$router.go(-1)
          }
        });
      },
      getCurrentDateTime() {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');
        return ` ${hours}:${minutes}:${seconds}`;
      },
      shopAdd() {
        this.$router.push("/productinfoDetails");
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          storeName: '',
          productCode: '',
          productFlag: '',
          productName: '',
        };
        this.resetForm("form");
        this.xlsFile = [];
        this.fileListN = [];
        this.tableData = []

      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getProductinfoNew();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      rechargeBtn() {
        this.dialogVisible = true
      },
    }
  };
</script>
<style scoped>
  .mesSty {
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    /* align-items: center; */
  }

  .cell-ellipsis {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    text-align: left;
  }

  .rechargeBtn {
    color: #fff;
    padding: 10px 20px;
    font-size: 14px;
    border-radius: 4px;
    background-color: #1890ff;
    margin-left: 10px;
    margin-right: 10px;
    cursor: pointer;
  }
</style>
